package com.cdtye.shuoh.config.schedule;

import com.alibaba.fastjson.JSONObject;
import com.cdtye.shuoh.domain.Frame.*;
import com.cdtye.shuoh.domain.enums.FrameType;
import com.cdtye.shuoh.domain.enums.PacketType;
import com.cdtye.shuoh.service.device.impl.DeviceDatasServiceImpl;
import com.cdtye.shuoh.util.text.DataConverter;
import com.cdtye.shuoh.util.text.DateUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;

@Component
public class Schedu {
  // @Scheduled(cron = "${schedule.cron:0/10 * * * * ? }")
    public void atmosphere() {
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("在 "+formatter.format(new Date())+" 执行了atmosphere方法。");
        generateAtmosphereData("11M221122WFGL0002");

    }

   // @Scheduled(cron = "${schedule.cron:0/10 * * * * ? }")
    public void photo() throws Exception {
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("在 "+formatter.format(new Date())+" 执行了atmosphere方法。");
        generatePhotoData("11M000000PV000001");
    }

   // @Scheduled(cron = "${schedule.cron:0/10 * * * * ? }")
    public void iceCover() {
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("在 "+formatter.format(new Date())+" 执行了iceCover方法。");
        gengerateIceCover("11M20230112FB0001");

    }
    //每30秒执行方法
    //@Scheduled(cron = "${schedule.cron:0/10 * * * * ? }")
    public void rang() {
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("在 "+formatter.format(new Date())+" 执行了temp方法。");
        //generateRANG("1582098515167","ed4ddd31509f4b4f9bf80952624ce10d");
        generateRANG("402891D75D4A0F68","b4973fac2edb4b13a8d2523f6dbbea43");
    }
    //每30秒执行方法
    //@Scheduled(cron = "${schedule.cron:0/10 * * * * ? }")
    public void dpmt() {
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("在 "+formatter.format(new Date())+" 执行了temp方法。");
        //("1582098515167","4f65e9c60dfa477b89f86c085dbd6d3a");
        generateDPMT("402891D75D4A0F68","412fd467ff2a45e3a5948db0a08e6ede");

    }

    //每30秒执行方法
    //@Scheduled(cron = "${schedule.cron:0/10 * * * * ? }")
    public void temp() {
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("在 "+formatter.format(new Date())+" 执行了temp方法。");
        //generateTemprature("1582098515167","491729faaac04bd0ad62878fc5da3041");
        generateTemprature("402891D75D4A0F68","8a0d458ed4d64c40a2c9e83200a23322");

    }

    //每30秒执行方法
    //@Scheduled(cron = "${schedule.cron:0/10 * * * * ? }")
    public void vibration() {
        SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("在 "+formatter.format(new Date())+" 执行了temp方法。");
        //generateVibration("1582098515167","fd53d2f6dadf45dbadf823b835002cf8");
        generateVibration("402891D75D4A0F68","c40015ece2f94c09b4c72434124f000a");

    }

    @Resource
    private DeviceDatasServiceImpl deviceDatasService;


    private void generatePhotoData(String deviceIdentification) throws Exception {
        String timeStamp = String.valueOf(Instant.now().getEpochSecond());
        ImageRequestEndFrame imageRequestEndFrame = new ImageRequestEndFrame("2","2",timeStamp,"a55a","0300","31314D3232313132325746474C30303032","06","06","06","06","06",deviceIdentification,"","");
        deviceDatasService.saveImageDataToTdengine(imageRequestEndFrame,"http://10.48.37.58:8888/group1/M00/00/00/CjAlOmQWl62AE0LoAAMKGPLQ4GA312.png");
    }
    private void generateAtmosphereData(String deviceIdentification){
        Random r = new Random();
        DecimalFormat df = new DecimalFormat( "0.00" );
        String timeStamp = String.valueOf(Instant.now().getEpochSecond());
        String average_windspeed_10min = String.valueOf(df.format(r.nextDouble()+30));
        String average_winddirection_10min = String.valueOf(df.format(r.nextDouble()+200));
        String max_windspeed = String.valueOf(df.format(r.nextDouble()*2+20));
        String extreme_windspeed = String.valueOf(df.format(r.nextDouble()*2+25));
        String standard_windspeed = String.valueOf(df.format(r.nextDouble()*2+22));
        String air_temperature = String.valueOf(df.format(r.nextDouble()*2+35));
        String humidity = String.valueOf(df.format(r.nextDouble()*2+54));
        String air_pressure = String.valueOf(df.format(r.nextDouble()*2+512));
        String precipitation = String.valueOf(df.format(r.nextDouble()*2+30));
        String precipitation_intensity = String.valueOf(df.format(r.nextDouble()*2+30));
        String radiation_intensity = String.valueOf(df.format(r.nextDouble()*2+30));
        AtmosphereFrame atmosphereFrame = new AtmosphereFrame("31314D3232313132325746474C30303032",timeStamp,average_windspeed_10min,average_winddirection_10min,max_windspeed,extreme_windspeed,standard_windspeed,air_temperature,humidity,air_pressure,precipitation,precipitation_intensity,radiation_intensity,"a55a","0300","31314D3232313132325746474C30303032","06","06","06","06","06",deviceIdentification);
        //todo 处理气象数据
        System.out.println(atmosphereFrame);
        deviceDatasService.processingAtmosphereFrame(atmosphereFrame);
    }

    private void gengerateIceCover(String deviceIdentification){
        Random r = new Random();
        DecimalFormat df = new DecimalFormat( "0.00" );
        String timeStamp = String.valueOf(Instant.now().getEpochSecond());
        String temperature = String.valueOf(df.format(r.nextDouble()*2+80));
        String icing_thickness = String.valueOf(df.format(r.nextDouble()*2+8));
        String icing_state = String.valueOf(r.nextDouble()>0.5?1:0);
        IceCoverFrame iceCoverFrame = new IceCoverFrame("31314D3232313132325746474C30303032",timeStamp,temperature,icing_thickness,icing_state,"a55a","0300","31314D3232313132325746474C30303032","02","03","02","0200","96",deviceIdentification);
        //todo 覆冰数据
        deviceDatasService.processingIceCoverFrame(iceCoverFrame);
    }

    private void handlerMessage(String message){
        message = message.replaceAll("\\s*", "").toUpperCase();
        String sync = message.substring(0,2*2);
        String packetLength = message.substring(2*2,2*4);
        String cmdId = message.substring(4*2,21*2);
        String frameType = message.substring(21*2,22*2);
        String packetType = message.substring(22*2,23*2);
        String frameNo = message.substring(23*2,24*2);
        String deviceIdentification = DataConverter.hexString2String(cmdId);
        String crc16 = message.substring(message.length()-6,message.length()-2);
        String end = message.substring(message.length()-2);
        System.out.println("Frame_type"+frameType);
        System.out.println("Packet_type"+packetType);
        System.out.println(deviceIdentification);
        //heartBeat Frame
         if(FrameType.VIDEO_REQUEST.getCode().equals(frameType) || FrameType.VIDEO_REQUEST_1.getCode().equals(frameType)){
            if(PacketType.PHOTO.getCode().equals(packetType)){
                //设备端发送请求上传图像数据报，平台端收到后原命令返回给设备端
//                String channelNo = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(24*2,25*2))));
//                String channelNoHex = message.substring(24*2,25*2);
//                String presettingNo = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(25*2,26*2))));
//                String presttingNoHex = message.substring(25*2,26*2);
//                String packetHigh = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(26*2,27*2))));
//                String packetLow = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(27*2,28*2))));
//                ImageRequestFrame imageRequestFrame = new ImageRequestFrame(channelNo,presettingNo,packetHigh,packetLow,sync,packetLength,cmdId,frameType,packetType,frameNo,crc16,end,deviceIdentification,channelNoHex,presttingNoHex);
            }else if(PacketType.IMAGE_DATA.getCode().equals(packetType)){
                //设备端接收验证无误后即开始上传图像数据报文
                String channelNo = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(24*2,25*2))));
                String channelNoHex = message.substring(24*2,25*2);
                String packetNo = String.valueOf(DataConverter.parseHexStr2Integer(message.substring(26*2,28*2)));
                String subpacketNo = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(28*2,30*2))));
                String presettingNo = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(25*2,26*2))));
                String presttingNoHex = message.substring(25*2,26*2);
                String sample = message.substring(30*2,message.length()-6);
                ImageDataFrame imageDataFrame = new ImageDataFrame(channelNo,presettingNo,packetNo,subpacketNo,sample,sync,packetLength,cmdId,frameType,packetType,frameNo,crc16,end,deviceIdentification,channelNoHex,presttingNoHex);
                //todo 处理图像数据
                //deviceDatasService.processingImageData(imageDataFrame);
            }else if(PacketType.IMAGE_DATA_END.getCode().equals(packetType)){
                String channelNo = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(24*2,25*2))));
                String channelNoHex = message.substring(24*2,25*2);
                String presettingNo = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(25*2,26*2))));
                String presttingNoHex = message.substring(25*2,26*2);
                String timeStamp = String.valueOf(DataConverter.hex2Long(DataConverter.reverseHex(message.substring(26*2,30*2))));
                ImageRequestEndFrame imageRequestEndFrame = new ImageRequestEndFrame(channelNo,presettingNo,timeStamp,sync,packetLength,cmdId,frameType,packetType,frameNo,crc16,end,deviceIdentification,channelNoHex,presttingNoHex);
                //todo 处理图像结束帧响应
                //return deviceDatasService.processingImageSendEnd(imageRequestEndFrame);
            }
         }
         if(FrameType.DATA_REQUEST.getCode().equals(frameType) && PacketType.ATMOSPHERE.getCode().equals(packetType)){
                String componentId = message.substring(24*2,41*2);
                String timeStamp = String.valueOf(Instant.now().getEpochSecond());
             System.out.println(timeStamp);
                String average_windspeed_10min = String.valueOf(DataConverter.parseHex2Float(DataConverter.reverseHex(message.substring(45*2,49*2))));
                String average_winddirection_10min = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(49*2,51*2))));
                String max_windspeed = String.valueOf(DataConverter.parseHex2Float(DataConverter.reverseHex(message.substring(51*2,55*2))));
                String extreme_windspeed = String.valueOf(DataConverter.parseHex2Float(DataConverter.reverseHex(message.substring(55*2,59*2))));
                String standard_windspeed = String.valueOf(DataConverter.parseHex2Float(DataConverter.reverseHex(message.substring(59*2,63*2))));
                String air_temperature = String.valueOf(DataConverter.parseHex2Float(DataConverter.reverseHex(message.substring(63*2,67*2))));
                String humidity = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(67*2,69*2))));
                String air_pressure = String.valueOf(DataConverter.parseHex2Float(DataConverter.reverseHex(message.substring(69*2,73*2))));
                String precipitation = String.valueOf(DataConverter.parseHex2Float(DataConverter.reverseHex(message.substring(73*2,77*2))));
                String precipitation_intensity = String.valueOf(DataConverter.parseHex2Float(DataConverter.reverseHex(message.substring(77*2,81*2))));
                String radiation_intensity = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(81*2,83*2))));
                AtmosphereFrame atmosphereFrame = new AtmosphereFrame(componentId,timeStamp,average_windspeed_10min,average_winddirection_10min,max_windspeed,extreme_windspeed,standard_windspeed,air_temperature,humidity,air_pressure,precipitation,precipitation_intensity,radiation_intensity,sync,packetLength,cmdId,frameType,packetType,frameNo,crc16,end,deviceIdentification);
                //todo 处理气象数据
                System.out.println(atmosphereFrame);
                deviceDatasService.processingAtmosphereFrame(atmosphereFrame);
            }else if(FrameType.DATA_REQUEST.getCode().equals(frameType) && PacketType.ICE_COVER.getCode().equals(packetType)){
                String componentId = message.substring(24*2,41*2);
                String timeStamp = String.valueOf(DataConverter.hex2Long(DataConverter.reverseHex(message.substring(41*2,45*2))));
                String temperature = String.valueOf(DataConverter.parseHex2Float(DataConverter.reverseHex(message.substring(45*2,49*2))));
                String icing_thickness = String.valueOf(DataConverter.parseHex2Float(DataConverter.reverseHex(message.substring(49*2,53*2))));
                String icing_state = String.valueOf(DataConverter.parseHexStr2Integer(DataConverter.reverseHex(message.substring(53*2,54*2))));
                IceCoverFrame iceCoverFrame = new IceCoverFrame(componentId,timeStamp,temperature,icing_thickness,icing_state,sync,packetLength,cmdId,frameType,packetType,frameNo,crc16,end,deviceIdentification);
                //todo 覆冰数据
                //return deviceDatasService.processingIceCoverFrame(iceCoverFrame);
            }

        return ;
    }

    private void generateTemprature(String gatewayId,String deviceId){
        Random r = new Random();
        DecimalFormat df = new DecimalFormat( "0.00" );
        Map<String,Object> result = new HashMap<>();
        Map<String,Object> body = new HashMap<>();
        Map<String,Object> services = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        data.put("temp",String.valueOf(df.format(r.nextDouble()*2+15.5)));
        data.put("version",1);
        data.put("volt_level",32);
        services.put("data",data);
        services.put("serviceId","analog");
        services.put("eventTime", DateUtils.getTimestampDate(String.valueOf(Instant.now().getEpochSecond()),"yyyyMMddHHmmss"));
        body.put("deviceId",deviceId);
        body.put("services", Arrays.asList(services));
        result.put("devices",Arrays.asList(body));
        try {
            deviceDatasService.processingDatasTopic(gatewayId,JSONObject.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void generateRANG(String gatewayId, String deviceId){
        Random r = new Random();
        DecimalFormat df = new DecimalFormat( "0.00" );
        Map<String,Object> result = new HashMap<>();
        Map<String,Object> body = new HashMap<>();
        Map<String,Object> services = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        data.put("rng_val",String.valueOf(df.format(r.nextDouble()*2+80)));
        data.put("version",1);
        data.put("volt_level",32);
        services.put("data",data);
        services.put("serviceId","analog");
        services.put("eventTime", DateUtils.getTimestampDate(String.valueOf(Instant.now().getEpochSecond()),"yyyyMMddHHmmss"));
        body.put("deviceId",deviceId);
        body.put("services", Arrays.asList(services));
        result.put("devices",Arrays.asList(body));
        try {
            deviceDatasService.processingDatasTopic(gatewayId,JSONObject.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void generateDPMT(String gatewayId, String deviceId){
        Random r = new Random();
        DecimalFormat df = new DecimalFormat( "0.00" );
        Map<String,Object> result = new HashMap<>();
        Map<String,Object> body = new HashMap<>();
        Map<String,Object> services = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        data.put("pos_val",String.valueOf(df.format(r.nextDouble()*2+80)));
        data.put("version",1);
        data.put("volt_level",32);
        services.put("data",data);
        services.put("serviceId","analog");
        services.put("eventTime", DateUtils.getTimestampDate(String.valueOf(Instant.now().getEpochSecond()),"yyyyMMddHHmmss"));
        body.put("deviceId",deviceId);
        body.put("services", Arrays.asList(services));
        result.put("devices",Arrays.asList(body));
        try {
            deviceDatasService.processingDatasTopic(gatewayId,JSONObject.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void generateVibration(String gatewayId,String deviceId){
        Random r = new Random();
        DecimalFormat df = new DecimalFormat( "0.00" );
        Map<String,Object> result = new HashMap<>();
        Map<String,Object> body = new HashMap<>();
        Map<String,Object> services = new HashMap<>();
        Map<String,Object> data = new HashMap<>();
        data.put("x_acc_val",r.nextInt(10)+115);
        data.put("y_acc_val",r.nextInt(10)+121);
        data.put("z_acc_val",r.nextInt(10)+126);
        data.put("ang_val",String.valueOf(df.format(r.nextDouble()*2+100)));
        data.put("version",1);
        data.put("volt_level",32);
        services.put("data",data);
        services.put("serviceId","analog");
        services.put("eventTime", DateUtils.getTimestampDate(String.valueOf(Instant.now().getEpochSecond()),"yyyyMMddHHmmss"));
        body.put("deviceId",deviceId);
        body.put("services", Arrays.asList(services));
        result.put("devices",Arrays.asList(body));
        try {
            deviceDatasService.processingDatasTopic(gatewayId,JSONObject.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
